package com.tl.bootmeter.controller;

import com.tl.bootmeter.pojo.User;
import com.tl.bootmeter.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService UserServiceImpl;

    /**
     * 登录
     * @param uname
     * @param upass
     * @param session
     * @return
     */
    @RequestMapping("login.do")
    public ModelAndView login(String uname, String upass, HttpSession session){
        User user = UserServiceImpl.checkLogin(uname,upass);
        System.out.print("User="+user);
        session.setAttribute("user",user);
        ModelAndView mode = new ModelAndView();
        mode.setViewName("index");
        return mode;
    }

    /**
     * 注销登录
     * 退出登录后需要重定向将url刷新为最开始的样子
     * @param request
     * @return
     */
    @RequestMapping("exit.do")
    public String exitUser(HttpServletRequest request){
        //注销session
        HttpSession session = request.getSession();
        session.invalidate();
//        ModelAndView mo = new ModelAndView();
//        mo.setViewName("login");
        //跳转回初始页面
        return "redirect:/";
//        return mo;
    }
    /**
     * 注册
     * @param uname
     * @param upass
     * @param unickName
     * @param ugender
     * @param uphone
     * @param district_id
     * @param station_id
     * @return
     */
    @RequestMapping("register.do")
    public ModelAndView register(String uname,String upass,String unickName,String ugender,String uphone,int district_id,int station_id){
        System.out.println("进入注册的控制器uname="+uname+",upass="+upass+",unickName="+unickName+",ugender="+ugender+",uphone="+uphone+",district_id="+district_id+",station_id="+station_id);
        int u = UserServiceImpl.insertUser(uname, upass, unickName, ugender, uphone, district_id, station_id);
        if(u != 0){
            ModelAndView mod = new ModelAndView();
            mod.setViewName("/index.jsp");
            return mod;
        }else{
            ModelAndView mod = new ModelAndView();
            mod.setViewName("/error.jsp");
            return mod;
        }

    }
    /**
     * 查询这个账户是否已经存在
     * @param uname
     * @return 返回的false没有查到，返回true查到了
     */
    @RequestMapping("selectUserByuname.do")
    @ResponseBody
    public boolean selectUserByuname(String uname){
        System.out.println("进入查询账户是否已经存在的控制器 "+uname);
        return UserServiceImpl.selectUserByuname(uname);
    }
}
